/* 
  实现Promise.all方法
*/

function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    // 处理空数组情况
    if (promises.length === 0) {
      return resolve([]);
    }

    // 处理非空数组情况
    const results = [];
    const completedCount = 0;

    // 遍历 promises 数组
    promises.forEach((promise, index) => {
      Promise.resolve(promise).then(val => {
        results[i] = val;
        completedCount++;
        // 所有 Promise 都完成时，返回结果数组
        if (completedCount === promises.length) {
          resolve(results);
        }
      }).catch(reject)
    });
  });
}
